import Req, { BASE_URL } from "./request";
import Taro from "@tarojs/taro";
import { getToken } from "./auth";
export function isEmpty(value) {
  // null 或 undefined
  if (value == null) return true;

  // 布尔值不算空
  if (typeof value === "boolean") return false;

  // 数字0不算空
  if (typeof value === "number") return false;

  // 空字符串
  if (typeof value === "string") return value.trim() === "";

  // 空数组
  if (Array.isArray(value)) return value.length === 0;

  // 空对象
  if (value.constructor === Object) return Object.keys(value).length === 0;

  // 其他情况
  return false;
}

export const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export const uploadImgConvertUrl = async (files: any[]) => {
  const env = Taro.getEnv();

  if (files && files.length) {
    const uploadTasks = files.map((item) => {
      const token = getToken();
      // 巨坑 Taro request 缺少boundary会上传失败，在h5中无法使用
      // return Taro.request({
      //   url: `${BASE_URL}/common/upload`,
      //   method: "POST",
      //   header: {
      //     Authorization: `Bearer ${token}`,
      //     "Content-Type": "multipart/form-data", // 必须这样设置
      //   },
      //   data: formData,
      // });
      if (!isEmpty(item.url) && item.url.startsWith(BASE_URL)) {
        return Promise.resolve({
          fileName: item.url.substring(BASE_URL.length),
        });
      } else if (env === Taro.ENV_TYPE.WEB) {
        const formData = new FormData();
        formData.append(
          "file",
          item.originalFileObj ?? item.file.originalFileObj
        );
        return fetch(`${BASE_URL}/common/upload`, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
          },
          body: formData,
        }).then((response) => response.json());
      } else {
        //否则就是小程序
        return Taro.uploadFile({
          url: `${BASE_URL}/common/upload`,
          filePath: item.url ?? item.path,
          fileName: "file",
          name: "file",
          header: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "multipart/form-data",
          },
          fail: (err) => {
            console.log(err);
          },
        });
      }
    });
    return await Promise.all(uploadTasks);
  }
  return [];
};

export const debounce = (func, wait) => {
  let timeout;
  return function (...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
};


export const goBack = () => {
  const pages = Taro.getCurrentPages()
  console.log(pages)
}